package com.sghd.candy.module.fight.manager;

import com.sghd.common.ramcache.IEntity;
import com.sghd.common.ramcache.PerPersist;
import com.sghd.common.ramcache.anno.Cached;
import com.sghd.common.ramcache.anno.CachedSizes;
import com.sghd.common.ramcache.anno.Persister;
import com.sghd.common.ramcache.anno.Persisters;
import com.sghd.common.ramcache.enhance.Enhance;
import com.sghd.common.utils.json.JsonUtils;
import com.sghd.pojo.candy.fight.enums.Grade;

import javax.persistence.*;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Allen
 * @date 2018/12/20
 */
@Entity
@Table(catalog = "bsdld")
@Cached(size = CachedSizes.DEFAULT, persister = @Persister(Persisters.PRE_10_MINUTE))
public class LevelInfo extends LevelId implements IEntity<Long>, PerPersist {
    @Id
    private Long playerId;
    @Transient
    private Map<String, Integer> levelGrade;
    @Lob
    private String levelGradeJson;

    public Long getPlayerId() {
        return playerId;
    }

    void setPlayerId(Long playerId) {
        this.playerId = playerId;
    }

    public Map<String, Integer> getLevelGrade() {
        return new HashMap<>(this.levelGrade);
    }

    void setLevelGrade(Map<String, Integer> levelGrade) {
        this.levelGrade = levelGrade;
    }

    public String getLevelGradeJson() {
        return levelGradeJson;
    }

    void setLevelGradeJson(String levelGradeJson) {
        this.levelGradeJson = levelGradeJson;
    }

    static LevelInfo valueOf(long playerId) {
        LevelInfo levelInfo = new LevelInfo();
        levelInfo.playerId = playerId;
        levelInfo.setBigLevelId(0);
        levelInfo.setLevelId(1);
        levelInfo.levelGrade = new HashMap<>();
        return levelInfo;
    }

    @Enhance
    void update(LevelId curLevelId, Grade grade) {
        this.levelGrade.put(curLevelId.getBigLevelId() + "-" + curLevelId.getLevelId(), grade.ordinal());
    }

    @Enhance
    void update(LevelId nextLevelId) {
        this.setBigLevelId(nextLevelId.getBigLevelId());
        this.setLevelId(nextLevelId.getLevelId());
    }

    @Override
    public Long getId() {
        return this.playerId;
    }

    @Override
    public void afterLoad() {
        this.levelGrade = JsonUtils.string2Map(this.levelGradeJson, String.class, Integer.class);
    }

    @Override
    public void beforePersist() {
        this.levelGradeJson = JsonUtils.object2String(this.levelGrade);
    }
}
